﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using ArbolandiaBL;
public partial class _Categories : System.Web.UI.Page
{
    String subcategoryid = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            subcategoryid = Request.QueryString["s"];
            pn.Value = ((Request.QueryString["pn"] == null || Request.QueryString["pn"] == "0") ? "1" : Request.QueryString["pn"].ToString());
            ApplyFilters(null, null);
        }
        LoadBanners();
    }

    protected void ApplyFilters(object sender, EventArgs e)
    {
        subcategoryid = Request.QueryString["s"];
        int subc; Int32.TryParse(subcategoryid, out subc);
        if (subcategoryid == null || subc == 0)
        {
            Response.Redirect("~/Default.aspx");
        }
        else
        {
            var service = new ServiceUI();

            //Top image
            //sectionTop.ImageUrl = "~/Images/Subsections/subsection" + subcategoryid + ".png";

            scid.Value = subcategoryid;

            var subcategory = service.GetSubCategoryDetail(Int32.Parse(subcategoryid));
            linkVerVideo.HRef = "http://www.youtube.com/embed/" + subcategory.UrlVideo;
            var category = service.GetCategorys().Where(x => x.Id == subcategory.IdCategory).First();
            var categories = service.GetCategorys();
            var subcategorieslist = new ServiceUI().GetSubcategorys(category.Id);
            //Top image
            sectionTop.ImageUrl = subcategory.ImageUrl;

            //lblRoute.Text = "INICIO / " + category.Name.ToUpper() + " / " + subcategory.Name.ToUpper();
            lblRoute.Text = "INICIO / "; lblRoute.NavigateUrl = "Default.aspx";
            lblRoute1.Text = category.Name.ToUpper() + " / "; lblRoute1.NavigateUrl = "Categories.aspx?c=" + category.Id;
            lblRoute2.Text = subcategory.Name.ToUpper();


            contenttext.InnerHtml = subcategory.MetaDescription;

            for (int i = 0; i < categories.Count(); i++)
            {
                drpCategories.Items.Add(new ListItem(categories[i].Name, categories[i].Id.ToString()));
                if (categories[i].Name.ToUpper() == category.Name.ToUpper())
                {
                    drpCategories.Items[i + 1].Selected = true;
                }
            }

            for (int i = 0; i < subcategorieslist.Count(); i++)
            {
                //left banner
                var div = new HtmlGenericControl("div");
                var hl = new HyperLink();

                if (subcategorieslist[i].Id.ToString() == subcategoryid.ToString())
                {
                    hl.ForeColor = System.Drawing.Color.Red;
                }

                hl.ID = "sc_" + subcategorieslist[i].Id.ToString();
                hl.Text = subcategorieslist[i].Name + " (" + subcategorieslist[i].TotalProducts + ")";
                hl.NavigateUrl = "~/Subcategories.aspx?s=" + subcategorieslist[i].Id.ToString();
                div.Controls.Add(hl);
                subcategories.Controls.Add(div);
            }

            var tmpproducts = new ServiceUI().GetProductsBySubCategory(Int32.Parse(subcategoryid));
            //Get Order by
            int orderby = 0; // 0 ningun 1 A-Z , 2 Z-A  , 3 Menor - mayor , 4 mayor - menor
            Int32.TryParse(drpOrderBy.SelectedValue, out orderby);
            var orderedList = new List<UIProductResume>();
            if (orderby == 1) { orderedList = tmpproducts.OrderBy(w => w.Name).ToList(); }
            else if (orderby == 2) { orderedList = tmpproducts.OrderByDescending(w => w.Name).ToList(); }
            else if (orderby == 3) { orderedList = tmpproducts.OrderBy(w => w.LowerPrice).ToList(); }
            else if (orderby == 4) { orderedList = tmpproducts.OrderByDescending(w => w.LowerPrice).ToList(); }
            else { orderedList = tmpproducts; }

            if (subcategory.IdCategory == 3 || subcategory.IdCategory == 4 || subcategory.IdCategory == 5)
            {
                var tmp2 = new ServiceUI().GetProductsVariousBySubCategory(Int32.Parse(subcategoryid));
                orderedList = (from p in tmp2
                               select new UIProductResume
                               {
                                   Id = p.Id,
                                   ImageUrl = p.ImageUrl,
                                   LowerPrice = p.LowerPrice,
                                   Name = p.Name,
                                   ShortDescription = p.ShortDescription
                               }).ToList();
            }

            var products = orderedList.Skip((Int32.Parse(pn.Value) - 1) * 5).Take(5).ToList();
            for (int i = 0; i < 20; i++)
            {
                //products.Add(new ServiceUI().GetProductsBySubCategory(Int32.Parse(subcategoryid)).First());
            }

            //Paginator
            Int32 total = products.Count();
            Int32 totalPages = total / 5;
            if (totalPages == 0)
            {
                totalPages = 1;
            }

            //Add anterior
            var pageanterior = new Label();
            pageanterior.Text = "« Anterior";
            pageanterior.Attributes.Add("style", "padding-left:10px; padding-right:10px;");
            pageanterior.Attributes.Add("onclick", "document.location.href='Subcategories.aspx?s=" + scid.Value + "&pn=" + (Int32.Parse(pn.Value) - 1).ToString() + "';");
            paginator.Controls.Add(pageanterior);

            //Add numbers
            for (int i = 1; i <= totalPages; i++)
            {
                var page = new HtmlGenericControl("span");
                page.InnerText = i.ToString();
                if (pn.Value == i.ToString())
                {
                    page.Attributes.Add("style", "background-color: #edeff4; color: gray; border: solid 1px gray;");
                }
                page.Attributes.Add("onclick", "document.location.href='Subcategories.aspx?s=" + scid.Value + "&pn=" + i.ToString() + "';");
                paginator.Controls.Add(page);
            }

            //Add siguiente
            var pagesiguiente = new HtmlGenericControl("span");
            pagesiguiente.InnerText = "Siguiente »";
            pagesiguiente.Attributes.Add("style", "padding-left:10px; padding-right:10px;");
            var tempnext = Int32.Parse(pn.Value) + 1;
            if (tempnext > totalPages)
            {
                tempnext = totalPages;
            }
            pagesiguiente.Attributes.Add("onclick", "document.location.href='Subcategories.aspx?s=" + scid.Value + "&pn=" + tempnext.ToString() + "';");
            paginator.Controls.Add(pagesiguiente);

            var br = new HtmlGenericControl("br");
            paginator.Controls.Add(br);

            //End of paginator

            //add products
            for (int i = 0; i < products.Count(); i++)
            {
                var div = new HtmlGenericControl("div");
                div.Attributes.Add("class", "product");
                div.Attributes.Add("style", "cursor:pointer;");
                div.Attributes.Add("onclick", "document.location.href='Detail.aspx?d=" + products[i].Id + "'");

                //Image
                var divImg = new HtmlGenericControl("div");
                divImg.Attributes.Add("class", "product-img");
                var img = new Image();
                img.Width = Unit.Percentage(100);
                img.Height = Unit.Percentage(100);
                //img.ImageUrl = "http://dataclinicc.web709.discountasp.net/arb/imagessite/notavaible.jpg";
                img.ImageUrl = products[i].ImageUrl;
                divImg.Controls.Add(img);

                //Middle
                var divMiddle = new HtmlGenericControl("div");
                divMiddle.Attributes.Add("class", "product-middle");
                var divMiddleText = new HtmlGenericControl("div");
                divMiddleText.Attributes.Add("class", "product-middle-name");
                divMiddleText.InnerText = products[i].Name;
                divMiddle.Controls.Add(divMiddleText);
                var divMiddleInfo = new HtmlGenericControl("div");
                divMiddleInfo.Attributes.Add("class", "product-middle-info");
                divMiddleInfo.InnerText = products[i].ShortDescription;
                divMiddle.Controls.Add(divMiddleInfo);
                var divMiddlePrice = new HtmlGenericControl("div");
                divMiddlePrice.Attributes.Add("class", "product-middle-price");
                divMiddlePrice.InnerText = "Desde " + products[i].LowerPrice.ToString("C") + " pesos";
                divMiddle.Controls.Add(divMiddlePrice);

                //Prefencias
                var divPrefs = new HtmlGenericControl("div");
                if (subcategory.IdCategory != 3 && subcategory.IdCategory != 4 && subcategory.IdCategory != 5)
                {
                    divPrefs.Attributes.Add("class", "product-preferencias");
                    var prefsTitle = new HtmlGenericControl("span");
                    prefsTitle.Attributes.Add("class", "product-preferencias-title");
                    prefsTitle.InnerText = "Preferencias";
                    divPrefs.Controls.Add(prefsTitle);
                    int max = 6;

                    for (int j = 0; j < products[i].ProductPreferences.Count; j++)
                    {
                        if (j >= max) { break; }
                        var prefImg = new Image();
                        prefImg.CssClass = "product-preferencias-imgs-" + ((j == 0 || j == 2 || j == 4) ? "left" : "right");
                        //prefImg.ImageUrl = "http://dataclinicc.web709.discountasp.net/arb/imagessite/notavaible.jpg";
                        prefImg.ImageUrl = products[i].ProductPreferences[j].ImageUrl;
                        prefImg.ToolTip = string.IsNullOrEmpty(products[i].ProductPreferences[j].Description) ? products[i].ProductPreferences[j].Name : products[i].ProductPreferences[j].Description;
                        divPrefs.Controls.Add(prefImg);
                    }
                }

                //var divfloracion = new HtmlGenericControl("div");
                //divfloracion.Attributes.Add("class", "product-floracion");

                //var divfrutos = new HtmlGenericControl("div");
                //divfrutos.Attributes.Add("class", "product-frutos");

                div.Controls.Add(divImg);
                div.Controls.Add(divMiddle);
                div.Controls.Add(divPrefs);
                productslist.Controls.Add(div);
                //productslist.Controls.Add(divfloracion);
                //productslist.Controls.Add(divfrutos);
            }
        }

    }
    public void pageNumberClick(object sender, EventArgs e)
    {
        try
        {

        }
        catch (Exception)
        {
            throw;
        }
    }

    protected void drpCategories_SelectedIndexChanged(object sender, EventArgs e)
    {
        Response.Redirect("~/Categories.aspx?c=" + ((DropDownList)sender).SelectedValue.ToString());
    }

    protected void LoadBanners()
    {
        var banner1 = new ServiceUI().GetBanner(BannerType.Top);
        for (int i = 0; i < banner1.Count(); i++)
        {
            var c = new HyperLink() { ImageUrl = banner1[i].Url, NavigateUrl = banner1[i].LinkUrl };
            var p = new HyperLink() { NavigateUrl = banner1[i].LinkUrl, Text = ((i + 1)).ToString() };
            c.Target = "_blank";
            p.Attributes.Add("rel", ((i + 1)).ToString());
            imagereel.Controls.Add(c);
            paging.Controls.Add(p);
        }
        var banner2 = new ServiceUI().GetBanner(BannerType.Middle);
        for (int i = 0; i < banner2.Count(); i++)
        {
            var c = new HyperLink() { ImageUrl = banner2[i].Url, NavigateUrl = banner2[i].LinkUrl };
            var p = new HyperLink() { NavigateUrl = banner2[i].LinkUrl, Text = ((i + 1)).ToString() };
            c.Target = "_blank";
            p.Attributes.Add("rel", ((i + 1)).ToString());
            imagereel2.Controls.Add(c);
            paging2.Controls.Add(p);
        }
        var banner3 = new ServiceUI().GetBanner(BannerType.Bottom);
        for (int i = 0; i < banner3.Count(); i++)
        {
            var c = new HyperLink() { ImageUrl = banner3[i].Url, NavigateUrl = banner3[i].LinkUrl };
            var p = new HyperLink() { NavigateUrl = banner3[i].LinkUrl, Text = ((i + 1)).ToString() };
            c.Target = "_blank";
            p.Attributes.Add("rel", ((i + 1)).ToString());
            imagereel3.Controls.Add(c);
            paging3.Controls.Add(p);
        }
    }
}